#!/bin/sh

schema_file='/etc/pdns/4.1.0_to_4.2.0_schema.pgsql.sql'

configs() {
	find /etc/pdns -name pdns.conf -print -o -name 'pdns-*.conf' -print
}

search_configs() {
	local includedir

	includedir="$(grep '^include-dir=' "$1" | cut -d = -f 2- | tail -n 1)"
	grep "^${2}=" "$1" ${includedir:+"$includedir"/*.conf} 2>/dev/null | tail -n 1
}

check_launch() {
	search_configs "$1" launch | grep -q gpgsql
}

psqlcmd() {
	/usr/bin/psql -1 -w -f "$schema_file" "$@"
}

pgsqlvars() {
	local cfg extra passfile password tmp
	cfg="$1"
	extra="$(search_configs "$cfg" gpgsql-extra-connection-parameters | cut -d = -f 2-)"
	tmp="$(mktemp -d -q)"
	passfile="${tmp:-/tmp}/pgsql.passfile"

	PGDATABASE="$(search_configs "$cfg" gpgsql-dbname | cut -d = -f 2-)"
	PGHOST="$(search_configs "$cfg" gpgsql-host | cut -d = -f 2-)"
	PGPORT="$(search_configs "$cfg" gpgsql-port | cut -d = -f 2-)"
	PGUSER="$(search_configs "$cfg" gpgsql-user | cut -d = -f 2-)"

	PGPASSFILE="$passfile"
	touch "$passfile"
	chmod 0600 "$passfile"
	password="$(search_configs "$cfg" gpgsql-password | cut -d = -f 2- | sed -e 's,['\'':],\\&,g')"
	printf > "$passfile" -- '*:*:*:*:%s\n' "$password"
	unset -v password

	for ev in DATABASE HOST PORT USER PASSFILE; do
		eval test -n \"\${PG${ev}}\" || continue
		export "PG${ev}"
	done

	psqlcmd ${extra:+"$extra"}

	for ev in DATABASE HOST PORT USER PASSFILE; do
		unset -v "PG${ev}"
	done
	rm -f "$passfile"
	rmdir "$tmp" 2>/dev/null
}

for c in $(configs); do
	check_launch "$c" || continue

	pgsqlvars "$c"
done; unset -v c

exit 0
